package com.zx.idc.backend.gui.api.management.infosecurity.violationwebsite.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.zx.idc.backend.gui.api.commom.entity.CommandModel;
import com.zx.idc.backend.gui.api.commom.entity.UploadModel;
import com.zx.idc.backend.gui.api.commom.entity.factory.CommandAckFactory;
import com.zx.idc.backend.gui.api.commom.template.NIdcFtpTemplate;
import com.zx.idc.backend.gui.api.management.infosecurity.violationwebsite.common.service.CommandRecordService;
import com.zx.idc.cache.ins.InsLogCountCacheService;
import com.zx.idc.common.attributes.FTPReportDataTypeEnum;
import com.zx.idc.common.attributes.NetCommunicationFileTypeEnum;
import com.zx.idc.common.attributes.SchemaFileNameEnum;
import com.zx.idc.common.attributes.SystemAttributes;
import com.zx.idc.common.constants.InstructionType;
import com.zx.idc.ds.common.constant.ReportStatusConstant;
import com.zx.idc.ds.ins.entity.InsAdminControl;
import com.zx.idc.ds.ins.entity.InsFilter;
import com.zx.idc.ds.ins.entity.InsMonitor;
import com.zx.idc.ds.ins.service.IInsAdminControlService;
import com.zx.idc.ds.ins.service.IInsFilterService;
import com.zx.idc.ds.ins.service.IInsMonitorService;
import com.zx.idc.xml.entity.CommandRecord;
import com.zx.idc.xml.entity.idccommandack.IdcCommandAck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.zx.idc.common.constants.IdcCommandAckTypeConstants.ILLEGAL_INFORMATION_MANAGEMENT_QUERY_INSTRUCTION;


/**
 * Created by hasee on 2019/2/19.
 * 违法管理指令执行记录指令
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CommandRecordServiceImpl implements CommandRecordService {

    private final static Logger LOG = LoggerFactory.getLogger(CommandRecordServiceImpl.class);

    @Autowired
    private IInsFilterService iInsFilterService;

    @Autowired
    private IInsMonitorService iInsMonitorService;

    @Autowired
    private InsLogCountCacheService insLogCountCacheService;

    @Autowired
    private NIdcFtpTemplate nIdcFtpTemplate;

    @Autowired
    private IInsAdminControlService iInsAdminControlService;

    @Override
    public void commandRecord(CommandRecord commandRecord, CommandModel commandModel) {
        long controlsId = commandRecord.getControlsId();
        List<IdcCommandAck> idcCommandAckList = new ArrayList<>();
        try {
            //记录管控指令
            InsAdminControl insAdminControl = new InsAdminControl()
                .setInsType(SystemAttributes.INS_TYPE_ILLEGAL_MANAGEMENT_INSTRUCTION_EXECUTION_RECORD)
                .setIdcId(commandModel.getIdcId())
                .setCreateTime(commandRecord.getTimeStamp())
                .setCommandId(String.valueOf(commandRecord.getCommandId()))
                .setReportStatus(ReportStatusConstant.NOT_REPORTED)
                .setInsContents(JSON.toJSONString(commandRecord));
            iInsAdminControlService.insert(insAdminControl);
            //根据违法信息安全管理指令的ID查询指令执行记录

            //过滤的
            String commandId = String.valueOf(controlsId);
            InsFilter insFilter = new InsFilter();
            insFilter.setId(commandId);
            InsFilter insFilterEntity = iInsFilterService.selectFirst(insFilter);

            //监控的
            InsMonitor insMonitor = new InsMonitor();
            insMonitor.setId(commandId);
            InsMonitor insMonitorEntity = iInsMonitorService.selectFirst(insMonitor);
            if (insFilterEntity != null) {
                for (String houseId : insFilterEntity.getHouseId().split(",")) {
                    long count = insLogCountCacheService.getCount(InstructionType.INS_FILTER, commandId);
                    IdcCommandAck idcCommandAck = CommandAckFactory.ackSuccess(
                        ILLEGAL_INFORMATION_MANAGEMENT_QUERY_INSTRUCTION,
                        commandModel,
                        (commandAck) ->
                            //从缓存获取统计数
                            commandAck.setHouseId(Long.parseLong(houseId))
                                .setCommandId(controlsId)
                                .setFilterCount(count)
                    );
                    idcCommandAckList.add(idcCommandAck);
                }

            } else if (insMonitorEntity != null) {
                for (String houseId : insMonitorEntity.getHouseId().split(",")) {
                    long count = insLogCountCacheService.getCount(InstructionType.INS_MONITOR, commandId);
                    IdcCommandAck idcCommandAck = CommandAckFactory.ackSuccess(
                        ILLEGAL_INFORMATION_MANAGEMENT_QUERY_INSTRUCTION,
                        commandModel,
                        (commandAck) ->
                            //从缓存获取统计数
                            commandAck.setHouseId(Long.parseLong(houseId))
                                .setCommandId(controlsId)
                                .setMonitorCount(count)
                    );
                    idcCommandAckList.add(idcCommandAck);
                }

            } else {
                IdcCommandAck idcCommandAck = CommandAckFactory.ackFail(
                    ILLEGAL_INFORMATION_MANAGEMENT_QUERY_INSTRUCTION,
                    commandModel,
                    "指令不存在",
                    (commandAck) ->
                        commandAck.setCommandId(controlsId)
                );
                idcCommandAckList.add(idcCommandAck);
            }

            //调用回调指令
            for (IdcCommandAck idcCommandAck : idcCommandAckList) {
                nIdcFtpTemplate.uploadXMLFile(
                    new UploadModel<>(
                        idcCommandAck,
                        SchemaFileNameEnum.INFO_SECURITY_MANAGEMENT,
                        FTPReportDataTypeEnum.FTP_VIOLATION_WEBSITE_MONITORING_RECORD,
                        NetCommunicationFileTypeEnum.INSTRUCTION_QUERY
                    )
                );
            }

        } catch (Exception e) {
            LOG.error("违法管理指令执行记录指令异常指令ID为：{}", commandRecord.getCommandId(), e);
            throw new RuntimeException(e);
        }


    }
}
